package com.yuejie.crawler;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yuejie.bean.ResultPojo;
import com.yuejie.bean.SongPojo;

public class LyricCrawlerInTing {
	private static final Logger connlogger = LoggerFactory.getLogger("connLogger");
	private static final Logger resultlogger = LoggerFactory.getLogger("resultLogger");
	// private static final Logger resultlogger =
	// LoggerFactory.getLogger("resultLogger");

	private final HttpClient httpClient;
	private final HttpContext context;

	public static void main(String[] args) {
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
		ClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
		HttpClient hc = new DefaultHttpClient(cm);

		LyricCrawlerInTing l = new LyricCrawlerInTing(hc);

		SongPojo s = new SongPojo();
		s.setId("123");
		s.setSinger_name("周治平");
		s.setSong_name("第七年");
		
		String lyric = l.getLyric(s).getLyric();
		System.out.println(lyric);
	}

	public LyricCrawlerInTing(HttpClient httpClient) {
		this.httpClient = httpClient;
		this.context = new BasicHttpContext();
	}

	public ResultPojo getLyric(SongPojo s) {
		String song_name = s.getSong_name().split("\\(")[0].toUpperCase();
		String singer_name = s.getSinger_name().split(",")[0];
		ResultPojo result = new ResultPojo();

		String qury_keyword;
		;
		try {
			qury_keyword = URLEncoder.encode(song_name + " " + singer_name, "UTF-8");

			String urlstring = "http://ting.baidu.com/search/lrc?key=" + qury_keyword;
			URI uri = new URI(urlstring);
			String pagecontent = this.executeGet(uri);
			Document doc = Jsoup.parse(pagecontent, "http://ting.baidu.com");
			Elements song_contents = doc.select(".song-content");
			
			if (song_contents.isEmpty()) {
				result.setCode(ResultPojo.StateCode.SONG_NOT_FOUND);
				resultlogger.error(s.getSinger_name() + ":" + s.getSong_name() + ":" + s.getId() + " [Empty search result for this song.]");
			} else {
				for (Element song_content : song_contents) {
					String song_name_in_content = song_content.select(".song-title").first()
							.select("em").html().toUpperCase();
					String singer_name_in_content = song_content.select(".author_list").first()
							.select("em").html();
					if (
							(singer_name.contains(singer_name_in_content) || singer_name_in_content.contains(singer_name))
							&& 
							(song_name_in_content.contains(song_name) || song_name.contains(song_name_in_content))
						) {
						
						String lrc_class = song_content.nextElementSibling().select(".lyric-action").first().select("a").last().className();
						String[] e = lrc_class.split("'");
						int length = e.length;
						String lrc_href = e[length-2];
						if("".equals(lrc_href)){
							continue;
						}else{
							return download_lyric(lrc_href);
						}
					} else {
						continue;
					}

				}
				result.setCode(ResultPojo.StateCode.ARTIST_NOT_MATCH);
			}

		}catch (MalformedURLException e) {
			result.setCode(ResultPojo.StateCode.CONNECT_ERROR);
			connlogger.error(s.getSinger_name()
					+ ":"
					+ s.getSong_name()
					+ ":"
					+ s.getId()
					+ " MalformedURLException in method (parseSearchResultPage)"
					+ e.toString());
		} 
		catch (UnsupportedEncodingException e) {
			result.setCode(ResultPojo.StateCode.CONNECT_ERROR);
			connlogger.error(s.getSinger_name()
					+ ":"
					+ s.getSong_name()
					+ ":"
					+ s.getId()
					+ " UnsupportedEncodingException in method (parseSearchResultPage)"
					+ e.toString());
		} catch (URISyntaxException e) {
			result.setCode(ResultPojo.StateCode.CONNECT_ERROR);
			connlogger.error(s.getSinger_name()
					+ ":"
					+ s.getSong_name()
					+ ":"
					+ s.getId()
					+ " URISyntaxException in method (parseSearchResultPage)"
					+ e.toString());
		} catch (ClientProtocolException e) {
			result.setCode(ResultPojo.StateCode.CONNECT_ERROR);
			connlogger.error(s.getSinger_name()
					+ ":"
					+ s.getSong_name()
					+ ":"
					+ s.getId()
					+ " ClientProtocolException in method (parseSearchResultPage)"
					+ e.toString());
		} catch (IOException e) {
			result.setCode(ResultPojo.StateCode.CONNECT_ERROR);
			connlogger.error(s.getSinger_name()
					+ ":"
					+ s.getSong_name()
					+ ":"
					+ s.getId()
					+ " IOException in method (parseSearchResultPage)"
					+ e.toString());
		}

		return result;
	}

	private String executeGet(URI uri) throws ClientProtocolException, IOException {
		HttpGet httpget = new HttpGet(uri);
		httpget.setHeader("User-Agent",
				"Mozilla/5.0 (Windows NT 6.1; rv:10.0.2) Gecko/20100101 Firefox/10.0.2");
		HttpResponse response = this.httpClient.execute(httpget, this.context);
		HttpEntity entity = response.getEntity();
		return EntityUtils.toString(entity, "UTF-8");

	}
	
	private ResultPojo download_lyric(String uri) throws URISyntaxException, ClientProtocolException, IOException{
		
		ResultPojo r = new ResultPojo();
		uri  = "http://ting.baidu.com" +uri;
		URI _uri = new URI(uri);
		String lyric = this.executeGet(_uri);
		
		r.setCode(200);
		r.setLyric(lyric);
		
		return r;
	}
}










